package com.sunnada.edu.business.salaryManage.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.sunnada.edu.business.salaryManage.dao.PayrollDao;
import com.sunnada.edu.business.setProcess.service.ProcessService;
import com.sunnada.edu.system.pub.common.AppContext;
import com.sunnada.edu.system.pub.common.EXCELObject;
import com.sunnada.edu.system.pub.dao.PubDao;
import com.sunnada.edu.system.pub.util.DateUtil;

@Service
@Transactional
public class PayrollServiceImpl implements PayrollService {
	private static final Logger logger = LoggerFactory.getLogger(PayrollServiceImpl.class);
	@Resource
	PayrollDao payrollDao;
	
	@Resource
	ProcessService processService;

	@Override
	public int getPayrollCots(HashMap<String, String> params) {
		return payrollDao.getPayrollCots(params);
	}

	@Override
	public List<?> findPayroll(HashMap<String, String> params) {
		return payrollDao.findPayroll(params);
	}

	@Override
	public String attendanceDelete(HashMap<String, String> params) {
		String msg = "";
		int num = payrollDao.attendanceDelete(params);
		if (num == 0) {
			msg = "删除失败!";
		}
		return msg;
	}

	@Override
	public String attenRecordAdd(HashMap<String, String> params) {
		String msg = "";
			int num = payrollDao.attenRecordAdd(params);
			if (num == 0) {
				msg = "0";// 失败
			} else {
				msg = "1";// 成功
			}

		return msg;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String attendanceUpdate(HashMap<String, String> params) {
		String msg = "";
			int num = payrollDao.attendanceUpdate(params);
			if (num == 0) {
				msg = "0";// 失败
			} else {
				msg = "1";// 成功
			}
		return msg;
	}

	@Override
	public Map attendanceByRecId(HashMap<String, String> params) {
		return payrollDao.attendanceByRecId(params);
	}
	@Override
	public void exportAttendance(HashMap<String, String> params, HttpServletRequest request, HttpServletResponse response) throws Exception {
		List dataList = payrollDao.exportAttendance(params);
		String recId = UUID.randomUUID().toString();
		String realPath = request.getSession().getServletContext().getRealPath("/file/temp");
		EXCELObject s = new EXCELObject();
		s.seteFilePath(realPath);
		String[] titH = { "姓名", "工号", "工种", "班组","考勤工时","累计工作量（件）", "计费方式", "单位薪酬","基本工资","奖励", "补贴", "考勤扣款","其他扣款","五险一金","个税", "应发", "实发","未发","工资状态"  };
		String[] titN = { "NAME","JOBNO","WORKTYPE","GROUPNAME","WORK_HOURS","WORK_QUANTITY","CHARGETYPE","UNITPAY","SALARY","WORK_REWARD","WORK_SUBSIDY","ATT_DEDUCTION","OTHER_DEDUCTION","WXYJ" ,"GS","SHOULD_GIVE","REAL_GIVE","NO_GIVE","REC_STATUS"};
		s.setFname("工资数据 "); // 临时文件名
		s.setTitle("工资数据"); // 大标题名称
		s.setTitH(titH);
		s.setTitN(titN);
		s.setDataList(dataList);
		File exportFile = null;
		exportFile = s.setData();
		String excelName = "工资数据" + DateUtil.getCurrentTime() + ".xls";
		s.exportExcel("工资数据", excelName, exportFile, request, response);

	}

	@Override
	public String payrollToAudit(HashMap<String, String> params) {
		String msg = "";
		//申请单ID
		String recId = UUID.randomUUID().toString();
		//根据流程类型回去，流程ID
		params.put("processType", "payrollApply");
		String processId = processService.getProcessId(params);
		if(("").equals(processId)){
			msg = "发放工资审核流程未配置，请先进行配置！";
			return msg;
		}
		params.put("recId", recId);
		params.put("processId", processId);
		
		//将发放工资的申请单入录数据库
		params.put("applyTime", DateUtil.getNowTime());
		int num = payrollDao.payrollToAudit(params);
		if(num > 0){
			//将发放工资申请单对应的员工入录数据库
			List<HashMap<String, String>> list = new ArrayList<>();
			String recIds = params.get("recIds");
			String recIdss[] = recIds.split(",");
			for(int i = 0; i < recIdss.length; i++){
				HashMap<String, String> map = new HashMap<>();
				map.put("applyId", recId);
				map.put("workerId", recIdss[i]);
				map.put("rejectState", "1");
				map.put("loginId", params.get("loginUserId"));
				list.add(map);
			}
			num = payrollDao.insertPayrollApplyWorkers(list);
			if(num > 0){
				//发起申请流程
				params.put("goDetailPage", "payrollApply");
				msg = processService.startProcess(params);
				
				if(("").equals(msg)){
					params.put("step", "1");
					msg = updateWorkerSalaryState(params);
				}
				
			}else{
				msg = "工资发放审核提交失败！";
			}
			
			
		}else{
			msg = "工资发放审核提交失败！";
		}
		return msg;
	}

	/*
	 * 提交审核后修改员工工资表状态
	 */
	private String updateWorkerSalaryState(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String msg = "";
		String sql = "";
		if (("1").equals(params.get("step"))) {
			sql = "update t_worker_salary set REC_STATUS = '2' where rec_time = '"
					+ params.get("beginTime")
					+ "' and WORKER_ID in ('"
					+ params.get("recIds").replaceAll(",", "','") + "')";
		} else {
			if(("1").equals(params.get("auditState"))){
				sql = "update t_worker_salary set REC_STATUS = '3' where rec_time = (select BEGIN_DATE from t_payroll_apply where rec_id = '"
						+ params.get("submitId")
						+ "') and WORKER_ID in (select WORKER_ID from t_payroll_apply_worker where apply_id = '"
						+ params.get("submitId")
						+ "' and REJECT_STATE = '1') ";
			}else if(("2").equals(params.get("auditState"))){
				sql = "update t_worker_salary set REC_STATUS = '1' where rec_time = (select BEGIN_DATE from t_payroll_apply where rec_id = '"
						+ params.get("submitId")
						+ "') and WORKER_ID in (select WORKER_ID from t_payroll_apply_worker where apply_id = '"
						+ params.get("submitId")
						+ "' and REJECT_STATE = '1') ";
			}
			
		}
		int num = dao.update(sql);
		if (num == 0) {
			msg = "工资发放审核提交失败！";
		}
		return msg;
	}

	@Override
	public List<?> getPayrollApplyByRecid(HashMap<String, String> params) {
		return payrollDao.getPayrollApplyByRecid(params);
	}

	@Override
	public int getPayrollApplyWorkerCots(HashMap<String, String> params) {
		return payrollDao.getPayrollApplyWorkerCots(params);
	}

	@Override
	public List<?> findPayrollApplyWorker(HashMap<String, String> params) {
		return payrollDao.findPayrollApplyWorker(params);
	}

	@Override
	public String audit(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String msg = "";
		msg = processService.audit(params);
		
		//判断是不是流程的最后一步，如果是进行员工工资表状态更改
		String sql = "select t.rec_id from t_process_staff t where t.parent_id = '" + params.get("auditId") + "'";
		List<?> list = dao.selectList(sql);
		if(list.size() == 0){
			params.put("step", "2");
			updateWorkerSalaryState(params);
		}
		return msg;
	}

	@Override
	public String saveRealPay(HashMap<String, String> params) {
		String msg = "";
		
		Map<String, Object> pMap = new HashMap<>();
		List<Map<String, String>> list = new ArrayList<>();
		String data = params.get("data");
		data = data.replaceAll("“", "\"");
		data = data.replaceAll("”", "\"");
		JSONArray processData=JSONArray.parseArray(data);
		for (int i = 0; i < processData.size(); i++) {
			Map<String,String> map = new HashMap<String, String>();
	    	map = (Map<String,String>)processData.get(i);
	    	list.add(map);
		}
		pMap.put("list", list);
		pMap.put("beginTime", params.get("beginTime"));
		int num = payrollDao.saveRealPay(pMap);
		if(num == 0){
			msg = "实发工资修改失败！";
		}
		return msg;
	}

}
